package com.xwaiy.xwaiyrpc.server.tcp;

import com.xwaiy.xwaiyrpc.protocol.ProtocolConstant;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.parsetools.RecordParser;

/**
 * @Author Xwaiy
 * @Date 2025/8/29 16:18
 **/
public class TcpBufferHandler implements Handler<Buffer> {

    private final RecordParser parser;

    public TcpBufferHandler(Handler<Buffer> handler) {
        parser = initRecordParser(handler);
    }

    @Override
    public void handle(Buffer buffer) {
        parser.handle(buffer);
    }

    private RecordParser initRecordParser(Handler<Buffer> handler) {
        RecordParser recordParser = RecordParser.newFixed(ProtocolConstant.MESSAGE_HEADER_LENGTH);

        recordParser.setOutput(new Handler<Buffer>() {
            int size = -1;

            Buffer result = Buffer.buffer();

            @Override
            public void handle(Buffer buffer) {
                if(-1==size) {
                    size = buffer.getInt(13);
                    recordParser.fixedSizeMode(size);
                    result.appendBuffer(buffer);
                }else{
                    result.appendBuffer(buffer);
                    handler.handle(result);
                    parser.fixedSizeMode(ProtocolConstant.MESSAGE_HEADER_LENGTH);
                    size = -1;
                    result = Buffer.buffer();
                }
            }
        });
        return recordParser;
    }
}
